<?php
class IM_C_Advertise extends IM_C_Base{
	public function start(){
		//$this->doCleanup();
		//$this->doCleanUpPics();
		parent::start();
		parent::showNavi();
		parent::showBottomLeftNavi();
		$this->registry->template->s_pageTitle = 'created by';
		$this->registry->template->s_pageTitleSide = '<h1></h1>';
		$this->registry->template->s_mainContent = $this->getMainContent();
		$this->registry->template->show('Public-Generic.php');
	}
	
	private function doCleanUpPics(){
		//check if the model id exists
		//if not exists delete all the pictures and everyhting else except dir
		$arr_o_pics = $this->o_em->getRepository('entities\IM_Model_picture')->getAll();
		
		if(!empty($arr_o_pics)){
			foreach($arr_o_pics as $o_pic){
				$i_modelId = $o_pic->getModelId();
				$o_model = $this->o_em->find('entities\IM_Model', $i_modelId);
				if(!isset($o_model) && empty($o_model)){
					//check the relpath content for consistency
					$this->o_em->remove($o_pic);
				}
			}
		}
		$this->o_em->flush();
	}
	
	private function doCleanUp(){
		$this->cleanUpFolder(C_FW_ABSPATH.'/im_images_mod/pictures');
		$this->cleanUpFolder(C_FW_ABSPATH.'/im_images_mod/thumbnails');
	}
	
	private function cleanUpFolder($s_path){
		$arr_dirContents = scandir($s_path);
		if(!empty($arr_dirContents)){
				foreach($arr_dirContents as $arr_dirContent){
					if(is_dir($s_path.'/'.$arr_dirContent) && $arr_dirContent != ".." && $arr_dirContent != "."){
						$arr_splitString =  explode('&', $arr_dirContent);
						if(isset($arr_splitString[0]) && isset($arr_splitString[1])){
							$i_modelId = EncryptionHandler::get()->doDecrypt($arr_splitString[1]);
							$o_model = $this->o_em->find('entities\IM_Model', $i_modelId);
							$s_filePath = $s_path . '/' .$arr_dirContent;
							if(is_dir($s_filePath)){
								$arr_pictures = scandir($s_filePath);
								if(!empty($arr_pictures)){
									if(!isset($o_model) && empty($o_model)){
										foreach($arr_pictures as $s_picturePath){
											$s_picturePath = $s_filePath.'/'.$s_picturePath;
											if(is_file($s_picturePath)){
												if(file_exists($s_picturePath)){
													unlink($s_picturePath);
												}
											}
										}
									}
								}
							}
							
							//remove the  dir
							if(!isset($o_model) && empty($o_model)){
								rmdir($s_path.'/'.$arr_dirContent);
							}
							
						}
					}
				}
		}
	}
	
	private function getMainContent(){
		$s_mainContent = '<p>developed by: claycode web consulting</p>';
		$s_mainContent .= '<p>contact us via emal at:<a href="mailto:claycodeweb@gmail.com?Subject=inquiry@imagency.ph">claycodeweb@gmail.com</a></p>';
		$s_mainContent .= '<p>copyright 2012 claycode web consulting</p>';
		return $s_mainContent;
	}
}